package com.leancloud.login.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.aries.ui.view.title.TitleBarView;
import com.leancloud.login.LoginPath;
import com.leancloud.login.R;
import com.leancloud.login.user.LoginBack;
import com.leancloud.login.user.NImageInfo;
import com.leancloud.login.user.UserGlobal;
import com.vise.utils.view.DialogUtil;
import com.vise.xsnow.event.BusManager;

import java.io.File;
import java.util.List;

import tech.com.commoncore.Config;
import tech.com.commoncore.LoginInterceptorImpl;
import tech.com.commoncore.base.BaseTitleActivity;
import tech.com.commoncore.event.LoginChangeEvent;
import tech.com.commoncore.manager.GlideManager;
import tech.com.commoncore.user.CurrentUser;
import tech.com.commoncore.utils.DataUtils;
import tech.com.commoncore.utils.ToastUtil;
import tech.com.commoncore.widget.photoPicker.MyPhotoPickerActivity;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

@Route(path = LoginPath.LOGIN_SETTINGSME, extras = LoginInterceptorImpl.LOGINCHECK)
public class PersonalSettingActivity extends BaseTitleActivity implements EasyPermissions.PermissionCallbacks {
    private static final int PRC_PHOTO_PICKER = 1;
    private static final int RC_CHOOSE_PHOTO = 2;

    private ImageView ivHeadIcon;
    private TextView tvNickname, tvPhone, tvSinge, tvSex;

    @Override
    public void setTitleBar(TitleBarView titleBar) {
        titleBar.setTitleMainText("个人设置").setBackground(getResources().getDrawable(R.drawable.btn_jb));
    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_setting;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handlerOnClick(v.getId());
            }
        };
        ivHeadIcon = findViewById(R.id.iv_head_icon);
        tvNickname = findViewById(R.id.tv_nickname);
        tvPhone = findViewById(R.id.tv_phone);
        tvSinge = findViewById(R.id.tv_singe);
        tvSex = findViewById(R.id.tv_sex);

        ivHeadIcon.setOnClickListener(clickListener);
        findViewById(R.id.ll_head_icon).setOnClickListener(clickListener);
        findViewById(R.id.ll_head_nick).setOnClickListener(clickListener);
        findViewById(R.id.ll_phone).setOnClickListener(clickListener);
        findViewById(R.id.ll_singe).setOnClickListener(clickListener);
        findViewById(R.id.ll_sex).setOnClickListener(clickListener);

        setUserInfo();
    }

    private void setUserInfo() {
        CurrentUser user = UserGlobal.getUserImp().getCurrentUser();
        String name = "";
        String headUrl = "";
        String number = "";
        String nikeName = "";
        String sign = "这个家伙很懒,什么也没留下";
        String sex = "保密";
        if (user == null) {
            name = "立即登录";
            nikeName = "立即登录";
            sign = "您还没有登录哦";
        } else {
            name = user.getNickName();
            headUrl = user.getAvatar();
            number = user.getMobile();
            nikeName = user.getNickName();
            sign = user.getSignature() == null ? sign : user.getSignature();
            if (user.getSex() == 1)
                sex = "男";
            if (user.getSex() == 2)
                sex = "女";
        }
        GlideManager.loadCircleImg(headUrl, ivHeadIcon, R.mipmap.icon_default_head);
        tvNickname.setText(nikeName);
        tvPhone.setText(number);
        tvSinge.setText(sign);
        tvSex.setText(sex);
    }

    private void handlerOnClick(int id) {
        if (id == R.id.ll_head_icon) {
            //nothing
        } else if (id == R.id.iv_head_icon) {
            choicePhotoWrapper();
        } else if (id == R.id.ll_head_nick) {
            showChangeNicknameDialog();
        } else if (id == R.id.ll_phone) {
            //nothing
        } else if (id == R.id.ll_singe) {
//            FastUtil.startActivity(this, SingeInputActivity.class);
        } else if (id == R.id.ll_sex) {
            final String[] sex = {"保密", "男", "女"};
            DialogUtil.dialogBuilder(mContext, "选择性别", null)
                    .setItems(sex, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, final int which) {
                            showLoading();
                            CurrentUser user = UserGlobal.getUserImp().getCurrentUser();
                            UserGlobal.getUserImp().modifyUserSex(user.getToken(), which, new LoginBack() {
                                @Override
                                public void onBack(Object o, String err) {
                                    hideLoading();
                                    if (err == null) {
                                        tvSex.setText(sex[which]);
                                        ToastUtil.show("修改成功");
                                    } else {
                                        ToastUtil.show("修改失败:" + err);
                                    }
                                }
                            });
                        }
                    }).create().show();
        }
    }

    //---------------------------------------------更改头像------------------------------------
    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    private void choicePhotoWrapper() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {
            File takePhotoDir = new File(Config.PHOTO_PATH);
            Intent photoPickerIntent = new MyPhotoPickerActivity.IntentBuilder(this)
                    .cameraFileDir(takePhotoDir) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
                    .maxChooseCount(1) // 图片选择张数的最大值
                    .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
                    .build();
            startActivityForResult(photoPickerIntent, RC_CHOOSE_PHOTO);
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.tip_photo_permissions_request), PRC_PHOTO_PICKER, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (requestCode == PRC_PHOTO_PICKER) {
            ToastUtil.show(R.string.tip_photo_permissions_denied);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == RC_CHOOSE_PHOTO) {
            upLoadPic(MyPhotoPickerActivity.getSelectedPhotos(data).get(0)); //保存图片
        }
    }

    //上传图片
    private void upLoadPic(String picUrl) {
        showLoading("正在上传...");
        final CurrentUser user = UserGlobal.getUserImp().getCurrentUser();
        UserGlobal.getUserImp().uploadImage(user.getToken(), picUrl, new LoginBack<NImageInfo>() {
            @Override
            public void onBack(final NImageInfo imageInfo, String err) {
                if (imageInfo != null) {
                    UserGlobal.getUserImp().modifyUserAvatar(user.getToken(), imageInfo.getComplete_url(), new LoginBack() {
                        @Override
                        public void onBack(Object o, String err) {
                            hideLoading();
                            if (err == null) {
                                ToastUtil.show("头像上传成功");
                                GlideManager.loadCircleImg(imageInfo.complete_url, ivHeadIcon, R.mipmap.icon_default_head);
                            } else {
                                ToastUtil.show("图片上传失败,请重新上传");
                            }
                        }
                    });
                } else {
                    hideLoading();
                    ToastUtil.show("图片上传失败,请重新上传");
                }
            }
        });
    }

    //----------------------更改昵称------------------
    private void showChangeNicknameDialog() {
//        int[] idList = {R.id.dialog_negative_tx, R.id.dialog_positive_tx};
//        KeenDialog.Builder builder = new KeenDialog.Builder()
//                .setContext(mContext)
//                .setLayoutId(R.layout.my_layout_nike_edit);
//        KeenDialog keenDialog = builder.create();
//        keenDialog.setClickListener(new OnKeenClickListener() {
//            @Override
//            public void onKeenClick(View view, View customView, Dialog dialog) {
//                if (view.getId() == R.id.dialog_positive_tx) {
//                    EditText editText = customView.findViewById(R.id.dialog_input_et);
//                    changeNick(editText.getText());
//                }
//                dialog.dismiss();
//            }
//        }, idList);
//        keenDialog.show();
    }

    private void changeNick(Editable nickName) {
        if (DataUtils.isEmpty(nickName)) {
            ToastUtil.show("昵称不能为空");
            return;
        }
        final String afterName = nickName.toString().trim();
        if (afterName.length() < 1 || afterName.length() > 12) {
            ToastUtil.show("请输入4-12个字符");
            return;
        }
        CurrentUser user = UserGlobal.getUserImp().getCurrentUser();
        UserGlobal.getUserImp().modifyUserNickName(user.getToken(), afterName, new LoginBack() {
            @Override
            public void onBack(Object o, String err) {
                hideLoading();
                if (err == null) {
                    ToastUtil.show("修改成功");
                    tvNickname.setText(afterName);
                    BusManager.getBus().post(new LoginChangeEvent(true));
                } else {
                    ToastUtil.show("修改失败,请检查网络后重试,");
                }
            }
        });
    }
}
